package com.feishi.core.util.qrcode.zxing;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wendell on 17-8-7.
 */
public class ZxingUtil {
    public static void main(String[] args) throws IOException, WriterException, NotFoundException {
        encode("http://www.baidu.com", new FileOutputStream("/tmp/zxing1.png"));
        System.out.println(decode(new FileInputStream("/tmp/zxing1.png")));;
    }

    public static void encode(String content, OutputStream out) throws WriterException, IOException {
        encode(content, 200, 200, out);
    }

    public static void encode(String content, int height, int width, OutputStream out) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
            BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        MatrixToImageWriter.writeToStream(bitMatrix, "png", out);
        out.flush();
    }

    public static String decode(InputStream in) throws NotFoundException, IOException {
        BufferedImage image = ImageIO.read(in);
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
        System.out.println(Arrays.toString(result.getRawBytes()));
        System.out.println(new String(result.getRawBytes()));
        return result.getText();
    }


}
